package com.custom.boredterminator.uiextends;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.StrictMode;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.AttributeSet;
import android.widget.Toast;

import com.custom.boredterminator.bean.Joke;
import com.custom.boredterminator.db.JokeDBHelper;
import com.custom.boredterminator.net.UpdateContent;
import com.custom.boredterminator.util.ConnectUtil;
import com.custom.boredterminator.wallpaper.CustomLiveWallpaper;

public class ButtonOptionPreference extends Preference {
	private PreferenceActivity parent;
	
	public ButtonOptionPreference(Context context) {
		super(context);
	}
	
	public ButtonOptionPreference(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}
	
	public ButtonOptionPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public void setActivity(PreferenceActivity parent) {
		this.parent = parent;
	}
	
	public boolean isPersistent() {
		return false;
	}
	
	public void setText(String summary) {
		this.setSummary(summary);
	}
	
	protected void onClick() {
		super.onClick();
		UpdateContent uc = new UpdateContent();
		JokeDBHelper jb = new JokeDBHelper(parent.getApplicationContext());
		if (canUpdate(parent.getApplicationContext())) {
			danteng();
			List<Joke> jokes = uc.updateContent(parent.getApplicationContext());
			jb.setJokes(jokes);
			Toast.makeText(parent.getApplicationContext(), "更新内容成功!",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(parent.getApplicationContext(), "网络链接设置存在问题，更新失败!",
					Toast.LENGTH_SHORT).show();
		}
	}
	
	private boolean canUpdate(Context context) {
		if ("all".equals(CustomLiveWallpaper.UPDATESET)
				&& ConnectUtil.isNetworkAvailable(context))
			return true;
		if ("wifi".equals(CustomLiveWallpaper.UPDATESET)
				&& ConnectUtil.isWifiEnabled(context))
			return true;
		return false;
	}
	
	@SuppressLint("NewApi")
	private void danteng() {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}
}
